package gbackup.command;


import gbackup.core.RemoteDirectory;
import gbackup.core.RemoteFile;
import gbackup.core.Shell;

import java.util.StringTokenizer;


public class RemoteChangeDirectoryCommand extends Command {
	private static final String PARENT = "..";
	private static final String CURRENT = ".";

	public RemoteChangeDirectoryCommand(Shell shell, String rawCommand) {
		super(shell, rawCommand);
	}

	@Override
	public void execute() {
		if (this._arguments.size() != 1) {
			this._outputPrintStream.println("Invalid Argument : [" + this._rawCommand + "]");
			return;
		}

		RemoteDirectory workingDirectory = null;
		String path = this._arguments.get(0);
		if (path.startsWith(RemoteFile.pathSeperator))
			workingDirectory = this._shell.getRemoteRootDirectory();
		else
			workingDirectory = this._shell.getRemoteWorkingDirectory();

		StringTokenizer st = new StringTokenizer(path, RemoteFile.pathSeperator);
		while (st.hasMoreTokens()) {
			String p = st.nextToken();

			if (p.equals(RemoteChangeDirectoryCommand.PARENT)) {
				workingDirectory = workingDirectory.getParent();
				continue;
			} else if (p.equals(RemoteChangeDirectoryCommand.CURRENT)) {
				continue;
			}

			boolean found = false;
			for (RemoteFile f : workingDirectory.getChildern()) {
				if (!f.isDirectory())
					continue;
				if (!f.getName().equals(p))
					continue;

				workingDirectory = (RemoteDirectory) f;
				found = true;
				break;
			}
			if (!found) {
				this._outputPrintStream.println("Directory Not Found : [" + this._arguments.get(0) + "]");
				return;
			}
		}

		this._shell.setRemoteWorkingDirectory(workingDirectory);
	}

}
